package com.hundsun.documentripper.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hundsun.documentripper.domain.dto.BaseResponse;
import com.hundsun.documentripper.domain.pojo.User;
import com.hundsun.documentripper.domain.pojo.UserProject;
import com.hundsun.documentripper.domain.query.BaseQuery;
import com.hundsun.documentripper.error.BaseException;
import com.hundsun.documentripper.mapper.UserMapper;
import com.hundsun.documentripper.mapper.UserProductMapper;
import com.hundsun.documentripper.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Note：
 *
 * @author ：mengjw
 * @description：用户接口实现
 * @date ：Created in 2021/1/26
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserProductMapper userProductMapper;

    @Override
    public void insertUser(User user) {
        // 判断用户编号是否已经存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("code", user.getCode());
        User example = userMapper.selectOne(wrapper);
        if (null != example) {
            throw new BaseException("1002");
        }
        userMapper.insert(user);
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateById(user);
    }

    @Override
    public User getUserById(String uuid) {
        User user = userMapper.selectById(uuid);
        user.setPassword("");
        return user;
    }

    @Override
    public IPage<User> getUserListByPage(BaseQuery baseQuery) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        IPage<User> userPage = userMapper.selectPage(new Page<User>(baseQuery.getCurrent(), baseQuery.getSize()), wrapper);
        for (User user : userPage.getRecords()) {
            user.setPassword("");
        }
        return userPage;
    }

    @Override
    public void deleteUser(String uuid) {
        userMapper.deleteById(uuid);
        // 删除用户后需要删除产品权限
        QueryWrapper<UserProject> wrapper = new QueryWrapper<>();
        wrapper.eq("user_uuid", uuid);
        userProductMapper.delete(wrapper);
    }

    @Override
    public BaseResponse<User> login(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("code", user.getCode());
        User example = userMapper.selectOne(wrapper);
        if (null == example) {
            return (BaseResponse<User>) BaseResponse.buildErrorResponse("1008");
        }
        if (!example.getPassword().equals(user.getPassword())) {
            return (BaseResponse<User>) BaseResponse.buildErrorResponse("1008");
        }
        example.setPassword("");
        return new BaseResponse<User>(example);
    }
}